<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        font: 13px Helvetica, Arial;
      }
      form {
        background: #000;
        padding: 3px;
        position: fixed;
        bottom: 0;
        width: 100%;
      }
      form input {
        border: 0;
        padding: 10px;
        width: 90%;
        margin-right: 0.5%;
      }
      form button {
        width: 9%;
        background: rgb(130, 224, 255);
        border: none;
        padding: 10px;
      }
      #messages {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }
      #messages li {
        padding: 5px 10px;
      }
      #messages li:nth-child(odd) {
        background: #eee;
      }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="" style="display: none" class="chat">
      <input id="m" autocomplete="off" />
      <button class="btn">Send</button>
    </form>

    <form action="" class="loginForm">
      <input class="name" autocomplete="off" />
      <button class="login">登录</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      let TYPE_INTO = 0;
      let TYPE_LEAVE = 1;
      let TYPE_MSG = 2;
      let name = document.getElementsByClassName("name")[0];
      let btn = document.getElementsByClassName("btn")[0];
      let login = document.getElementsByClassName("login")[0];
      let ul = document.getElementById("messages");

      //   点击登录
      login.onclick = function (event) {
        event.preventDefault();
        socket.emit("into", name.value);
        document.getElementsByClassName("chat")[0].style.display = "block";
        document.getElementsByClassName("loginForm")[0].style.display = "none";
      };

      //   发送消息
      btn.onclick = function (event) {
        event.preventDefault();
        let msg = document.getElementById("m");
        socket.emit("msg", {
          name: name.value,
          type: TYPE_MSG,
          msg: msg.value,
        });
      };

      //   登录消息
      socket.on("into", function (msg) {
        li = document.createElement("li");
        msg = document.createTextNode(msg.msg);
        li.appendChild(msg);
        li.style.color = "green";
        ul.appendChild(li);
      });

      //   聊天消息
      socket.on("msg", function (msg) {
        li = document.createElement("li");
        msg = document.createTextNode(`${msg.name} : ${msg.msg}`);
        li.appendChild(msg);
        li.style.color = "red";
        ul.appendChild(li);
      });
    </script>
  </body>
</html>
